<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search as IconSearch, Calendar as IconCalendar, Plus as IconPlus, View as IconView, Edit, Delete } from '@element-plus/icons-vue'
import outboundApi from '@/api/outbound'
import itemApi from '@/api/item'
import warehouseApi from '@/api/warehouse'
import type { OutboundRecordInfo, OutboundRecordListParams, CreateOutboundRecordParams, UpdateOutboundRecordParams } from '@/api/outbound'
import type { ItemInfo } from '@/api/item'
import type { WarehouseInfo } from '@/api/warehouse'
import type { KnownAsTypeMap } from 'vite/types/importGlob.js'

const tableData = ref<OutboundRecordInfo[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const searchParams = ref<OutboundRecordListParams>({
  page: currentPage.value,
  pageSize: pageSize.value,
  itemId: undefined,
  warehouseId: undefined,
  startTime: undefined,
  endTime: undefined,
})

const editFormRef = ref();
const editForm = ref({
  outboundId: undefined as number | undefined,
  itemId: undefined as number | undefined,
  warehouseId: undefined as number | undefined,
  quantity: undefined as number | undefined,
  unitPrice: undefined as number | undefined,
  outboundTime: undefined as string | undefined,
  operatorId: undefined as number | undefined,
  operatorName: undefined as string | undefined,
});

const editDialogVisible = ref(false);
const itemOptions = ref<ItemInfo[]>([])
const warehouseOptions = ref<WarehouseInfo[]>([])
const dateRange = ref<[Date, Date] | null>(null)

// 创建出库记录相关数据
const createDialogVisible = ref(false)
const createFormRef = ref()
const createForm = ref<CreateOutboundRecordParams>({
  itemId: undefined as any,
  warehouseId: undefined as any,
  quantity: 0,
  unitPrice: 0,
  recipient: '',
  notes: '',
})

// 查看出库记录详情相关数据
const detailDialogVisible = ref(false)
const outboundRecordDetail = ref<OutboundRecordInfo | null>(null)
const detailLoading = ref(false)


const validateQuantity = (rule: any, value: any, callback: any) => {
  if (value === null || value === undefined || value === '') {
    return callback(new Error('请输入数量'));
  }
  if (typeof value !== 'number' || isNaN(value)) {
    return callback(new Error('数量必须是数字'));
  }
  if (value <= 0) {
    return callback(new Error('数量必须大于0')); // This message matches the image
  }
  callback();
};

const validateUnitPrice = (rule: any, value: any, callback: any) => {
   if (value === null || value === undefined || value === '') {
    return callback(new Error('请输入单价'));
  }
  if (typeof value !== 'number' || isNaN(value)) {
    return callback(new Error('单价必须是数字'));
  }
  if (value < 0) {
    return callback(new Error('单价不能小于0')); // This message matches the image
  }
  callback();
};

// 创建表单验证规则
const createFormRules = {
  item_id: [
    { required: true, message: '请选择物品', trigger: 'change' }
  ],
  warehouseId: [
    { required: true, message: '请选择仓库', trigger: 'change' }
  ],
  quantity: [
    { required: true,  validator: validateQuantity, message: '请输入出库数量', trigger: 'blur' }
  ],
  unitPrice: [
    { required: true, validator: validateUnitPrice,message: '请输入物品单价', trigger: 'blur' },
  ],
  recipient: [
    { required: true, message: '请输入领用人/接收单位', trigger: 'blur' },
    { max: 100, message: '长度不能超过 100 个字符', trigger: 'blur' }
  ],
  notes: [
    { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' }
  ]
}

// 编辑表单验证规则
const editFormRules = {
  itemId: [
    { required: true, message: '请选择物品', trigger: 'change' }
  ],
  warehouseId: [
    { required: true, message: '请选择仓库', trigger: 'change' }
  ],
  quantity: [
    { required: true, validator: validateQuantity, trigger: 'blur' }
  ],
  unitPrice: [
    { required: true, validator: validateUnitPrice, trigger: 'blur' }
  ],
  outboundTime: [
    { required: true, message: '请选择出库时间', trigger: 'change' }
  ]
};

// 计算总金额
const calculatedTotalAmount = computed(() => {
  return (createForm.value.quantity || 0) * (createForm.value.unitPrice || 0);
});

// 获取出库记录列表
const getOutboundRecordList = async () => {
  loading.value = true
  try {
    const params: OutboundRecordListParams = {
      ...searchParams.value,
      page: currentPage.value,
      pageSize: pageSize.value,
    }
     // 处理日期范围
    if (dateRange.value && dateRange.value.length === 2) {
      // 确保日期是 UTC 格式或后端需要的格式
      params.startTime = dateRange.value[0]?.toISOString() || undefined;
      params.endTime = dateRange.value[1]?.toISOString() || undefined;
    } else {
      params.startTime = undefined;
      params.endTime = undefined;
    }

    const res = await outboundApi.getOutboundRecordList(params)
    tableData.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    ElMessage.error('获取出库记录列表失败')
  } finally {
    loading.value = false
  }
}

// 获取物品选项
const getItemOptions = async () => {
  try {
    const res = await itemApi.getItemList({ page: 1, pageSize: 1000 })
    itemOptions.value = res.data.list
  } catch (error) {
    // 忽略错误，不影响主流程
  }
}

// 获取仓库选项
const getWarehouseOptions = async () => {
  try {
    const res = await warehouseApi.getWarehouseList({ pageNum: 1, pageSize: 1000 })
    warehouseOptions.value = res.data.list
  } catch (error) {
    // 忽略错误，不影响主流程
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  getOutboundRecordList()
}

// 处理页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getOutboundRecordList()
}

// 处理每页条数变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  getOutboundRecordList()
}

// 处理日期范围变化
const handleDateChange = (val: [Date, Date] | null) => {
  dateRange.value = val;
}

// 打开创建出库记录对话框
const handleCreate = () => {
  createDialogVisible.value = true
  // 重置表单数据
  createForm.value = {
    itemId: undefined as any,
    warehouseId: undefined as any,
    quantity: 0,
    unitPrice: 0,
    recipient: '',
    notes: '',
  };
  // 重置表单验证状态
  createFormRef.value?.resetFields();
}

// 提交创建出库记录表单
const handleSubmit = async () => {
  if (!createFormRef.value) return
  
  await createFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        await outboundApi.createOutboundRecord(createForm.value)
        ElMessage.success('创建出库记录成功')
        createDialogVisible.value = false
        getOutboundRecordList() // 刷新列表
      } catch (error) {
        ElMessage.error('创建出库记录失败')
      }
    }
  })
}

// 取消创建
const handleCancel = () => {
  createDialogVisible.value = false
  createFormRef.value?.resetFields()
}

// 查看出库记录详情
const handleViewDetail = async (row: OutboundRecordInfo) => {
  loading.value = true;
  try {
    const response = await outboundApi.getOutboundRecordById(row.outboundId);
    outboundRecordDetail.value = response.data as unknown as OutboundRecordInfo;
    detailDialogVisible.value = true;
  } catch (error) {
    console.error('Error fetching outbound record detail:', error);
    ElMessage.error('获取出库记录详情失败');
  } finally {
    loading.value = false;
  }
};

// 关闭详情对话框
const handleCloseDetail = () => {
  detailDialogVisible.value = false;
  outboundRecordDetail.value = null;
};

// Add handleEdit function
const handleEdit = async (row: OutboundRecordInfo) => {
   loading.value = true;
   try {
      const response = await outboundApi.getOutboundRecordById(row.outboundId);
      if (response.data.code === 200) {
         // Populate the edit form with fetched data
         editForm.value = {
            outboundId: response.data.data.outboundId,
            itemId: response.data.data.itemId,
            warehouseId: response.data.data.warehouseId,
            quantity: response.data.data.quantity,
            unitPrice: response.data.data.unitPrice,
            // Format outboundTime for el-date-picker if needed
            outboundTime: response.data.data.outboundTime, // Assuming backend returns a format el-date-picker understands or needs formatting
            operatorId: response.data.data.operatorId,
            operatorName: response.data.data.operator?.username, // Display operator name
         };
         editDialogVisible.value = true;
      } else {
         ElMessage.error(response.data.message || '获取出库记录详情失败');
      }
   } catch (error) {
      console.error('Error fetching outbound record for edit:', error);
      ElMessage.error('获取出库记录信息失败');
   } finally {
      loading.value = false;
   }
};

// Add handleEditSubmit function
const handleEditSubmit = () => {
   if (!editFormRef.value) return;
   
   editFormRef.value.validate(async (valid: boolean) => {
      if (valid) {
         try {
            // Prepare data to send, excluding operatorName which is only for display
            const dataToSend: UpdateOutboundRecordParams = {
               outboundId: Number(editForm.value.outboundId),
               itemId: Number(editForm.value.itemId),
               warehouseId: Number(editForm.value.warehouseId),
               quantity: Number(editForm.value.quantity),
               unitPrice: Number(editForm.value.unitPrice),
               outboundTime: editForm.value.outboundTime || '',
               operatorId: Number(editForm.value.operatorId),
            };

            const response = await outboundApi.createOutboundRecord(dataToSend);
            if (response.data.code === 200) {
               ElMessage.success('更新出库记录成功');
               editDialogVisible.value = false;
               getOutboundRecordList(); // Refresh the list
            } else {
               ElMessage.error(response.data.message || '更新出库记录失败');
            }
         } catch (error: any) {
            console.error('Error updating outbound record:', error);
            ElMessage.error('更新出库记录失败');
         }
      }
   });
};

// Add handleEditCancel function
const handleEditCancel = () => {
   editDialogVisible.value = false;
   if (editFormRef.value) {
      editFormRef.value.resetFields();
   }
   editForm.value = {
      outboundId: undefined,
      itemId: undefined,
      warehouseId: undefined,
      quantity: undefined,
      unitPrice: undefined,
      outboundTime: undefined,
      operatorId: undefined,
      operatorName: undefined,
   };
};

// Add handleDelete function
const handleDelete = (row: OutboundRecordInfo) => {
   ElMessageBox.confirm(
      `确定删除ID为 ${row.outboundId} 的出库记录吗？`,
      '提示',
      {
         confirmButtonText: '确定',
         cancelButtonText: '取消',
         type: 'warning',
      }
   )
   .then(async () => {      try {
         const response = await outboundApi.createOutboundRecord(row.outboundId);
         if (response.data.code === 200) {
            ElMessage.success('删除成功');
            getOutboundRecordList(); // Refresh the list
         } else {
            ElMessage.error(response.data.message || '删除失败');
         }
      } catch (error: any) {
         console.error('Error deleting outbound record:', error);
          // Check for specific foreign key constraint error message if applicable
         if (error.response && error.response.data && error.response.data.message && error.response.data.message.includes('Cannot delete or update a parent row: a foreign key constraint fails')) {
            ElMessage.error('删除失败：该记录被其他数据引用。');
          } else {
             ElMessage.error('删除出库记录失败');
          }
      }
   })
   .catch(() => {
      // User cancelled deletion
   });
};

onMounted(() => {
  getItemOptions()
  getWarehouseOptions()
  getOutboundRecordList()
})
</script>

<template>
  <div class="outbound-record-list-container">
    <div class="search-bar">
      <el-select
        v-model="searchParams.itemId"
        placeholder="请选择物品"
        clearable
        class="search-select"
        style="width: 180px"
      >
        <el-option
          v-for="item in itemOptions"
          :key="item.itemId"
          :label="item.itemName"
          :value="item.itemId"
        />
      </el-select>
      <el-select
        v-model="searchParams.warehouseId"
        placeholder="请选择仓库"
        clearable
        class="search-select"
        style="width: 180px"
      >
        <el-option
          v-for="warehouse in warehouseOptions"
          :key="warehouse.warehouseId"
          :label="warehouse.warehouseName"
          :value="warehouse.warehouseId"
        />
      </el-select>

      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :prefix-icon="IconCalendar"
        @change="handleDateChange"
      />

      <el-button type="primary" :icon="IconSearch" @click="handleSearch">搜索</el-button>
      <el-button type="success" :icon="IconPlus" @click="handleCreate">新增出库</el-button>
    </div>

    <el-table :data="tableData" border loading="loading" style="width: 100%" class="outbound-record-table">
      <el-table-column prop="outboundId" label="记录ID" width="80" />
      <el-table-column label="物品" width="150">
        <template #default="{ row }">
          {{ row.item?.itemName || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="仓库" width="150">
        <template #default="{ row }">
          {{ row.warehouse?.warehouseName || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="quantity" label="数量" width="80" />
      <el-table-column prop="unitPrice" label="单价" width="100" />
      <el-table-column prop="totalAmount" label="总金额" width="120" />
      <el-table-column prop="recipient" label="领用人/接收单位" width="150" show-overflow-tooltip />
      <el-table-column label="操作员" width="120">
         <template #default="{ row }">
          {{ row.operator?.realName || row.operator?.username || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="outboundTime" label="出库时间" width="180" />
      <el-table-column prop="notes" label="备注" min-width="200" show-overflow-tooltip />
      <el-table-column prop="createdAt" label="创建时间" width="180" />
       <el-table-column label="操作" width="180" fixed="right">
         <template #default="{ row }">
            <el-button
              type="primary"
              :icon="IconView"
              circle
              @click="handleViewDetail(row)"
            />
            <el-button
              type="warning"
              :icon="Edit"
              circle
              @click="handleEdit(row)"
            />
            <el-button
              type="danger"
              :icon="Delete"
              circle
              @click="handleDelete(row)"
            />
         </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :disabled="!total"
      />
    </div>
  </div>

  <!-- 创建出库记录对话框 -->
  <el-dialog
    v-model="createDialogVisible"
    title="新增出库记录"
    width="500px"
    @close="handleCancel"
  >
    <el-form
      ref="createFormRef"
      :model="createForm"
      :rules="createFormRules"
      label-width="100px"
    >
      <el-form-item label="物品" prop="itemId">
        <el-select v-model="createForm.itemId" placeholder="请选择物品">
          <el-option
            v-for="item in itemOptions"
            :key="item.itemId"
            :label="item.itemName"
            :value="item.itemId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="仓库" prop="warehouseId">
        <el-select v-model="createForm.warehouseId" placeholder="请选择仓库">
          <el-option
            v-for="warehouse in warehouseOptions"
            :key="warehouse.warehouseId"
            :label="warehouse.warehouseName"
            :value="warehouse.warehouseId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="数量" prop="quantity">
        <el-input-number
          v-model="createForm.quantity"
          :min="1"
          :controls="false"
          placeholder="请输入出库数量"
        />
      </el-form-item>
      <el-form-item label="单价" prop="unitPrice">
        <el-input-number
          v-model="createForm.unitPrice"
          :min="0"
          :controls="false"
          :precision="2"
          placeholder="请输入物品单价"
        />
      </el-form-item>
      <el-form-item label="总金额">
         {{ calculatedTotalAmount.toFixed(2) }}
      </el-form-item>
      <el-form-item label="领用人/接收单位" prop="recipient">
        <el-input v-model="createForm.recipient" placeholder="请输入领用人或接收单位" />
      </el-form-item>
       <el-form-item label="备注" prop="notes">
        <el-input
          v-model="createForm.notes"
          type="textarea"
          :rows="3"
          placeholder="请输入备注信息"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定出库</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 出库记录详情对话框 -->
  <el-dialog
    v-model="detailDialogVisible"
    title="出库记录详情"
    width="600px"
    @close="handleCloseDetail"
  >
    <div loading="detailLoading">
      <template v-if="outboundRecordDetail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="记录ID">
            {{ outboundRecordDetail.outboundId }}
          </el-descriptions-item>
          <el-descriptions-item label="物品">
            {{ outboundRecordDetail.item?.itemName || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="仓库">
            {{ outboundRecordDetail.warehouse?.warehouseName || '-' }}
          </el-descriptions-item>
           <el-descriptions-item label="数量">
            {{ outboundRecordDetail.quantity }}
          </el-descriptions-item>
          <el-descriptions-item label="单价">
            {{ outboundRecordDetail.unitPrice.toFixed(2) }}
          </el-descriptions-item>
          <el-descriptions-item label="总金额">
            {{ outboundRecordDetail.totalAmount.toFixed(2) }}
          </el-descriptions-item>
          <el-descriptions-item label="领用人/接收单位">
            {{ outboundRecordDetail.recipient || '-' }}
          </el-descriptions-item>
           <el-descriptions-item label="操作员">
            {{ outboundRecordDetail.operator?.realName || outboundRecordDetail.operator?.username || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="出库时间">
            {{ outboundRecordDetail.outboundTime }}
          </el-descriptions-item>
          <el-descriptions-item label="备注">
            {{ outboundRecordDetail.notes || '-' }}
          </el-descriptions-item>
           <el-descriptions-item label="创建时间">
            {{ outboundRecordDetail.createdAt }}
          </el-descriptions-item>
        </el-descriptions>
      </template>
    </div>
  </el-dialog>

  <!-- Add Edit Outbound Record Dialog -->
  <el-dialog
    title="编辑出库记录"
    v-model="editDialogVisible"
    width="500px"
    @close="handleEditCancel"
  >
    <el-form
      :model="editForm"
      :rules="editFormRules"
      ref="editFormRef"
      label-width="100px"
    >      <el-form-item label="物品" prop="itemId">
        <el-select v-model="editForm.itemId" placeholder="请选择物品" filterable>
          <el-option
            v-for="item in itemOptions"
            :key="item.itemId"
            :label="item.itemName"
            :value="item.itemId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="仓库" prop="warehouseId">
        <el-select v-model="editForm.warehouseId" placeholder="请选择仓库" filterable>
          <el-option
            v-for="warehouse in warehouseOptions"
            :key="warehouse.warehouseId"
            :label="warehouse.warehouseName"
            :value="warehouse.warehouseId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="数量" prop="quantity">
        <el-input-number v-model="editForm.quantity" :min="1"></el-input-number>
      </el-form-item>
      <el-form-item label="单价" prop="unitPrice">
        <el-input-number v-model="editForm.unitPrice" :min="0"></el-input-number>
      </el-form-item>       <el-form-item label="出库时间" prop="outboundTime">
          <el-date-picker
            v-model="editForm.outboundTime"
            type="datetime"
            placeholder="选择日期和时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      <el-form-item label="总金额">
        <el-input v-model="calculatedTotalAmount" readonly />
      </el-form-item>
       <el-form-item label="操作员">
         <el-input v-model="editForm.operatorName" readonly />
       </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleEditCancel">取 消</el-button>
        <el-button type="primary" @click="handleEditSubmit">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.outbound-record-list-container {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-select {
  width: 180px;
}

.outbound-record-table {
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.el-select,
.el-input-number {
  width: 100%;
}

/* 可以添加更多样式来优化表格和表单的布局和外观 */
</style>